<template>
  <div style="padding: 15px;">
    <vxe-toolbar id="staffId" :setting="{storage: true}"  :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcAdd">新增</el-button>
        <el-button :loading="exportAllloading" @click="AllDataEventAll">导出全部</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      highlight-hover-row
      row-id="id"
      :align="allAlign"
      height="700"
      :loading="loading"
      :data="tableData"
      remote-sort
      @sort-change="sortList"
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column  :formatter="groupNameFormatter"  title="所属机构" min-width="350" sortable />
        <template v-slot:header="{ column }">
          <groupSelect :organization="organization" @setGroupCode="setOrgCode" />
        </template>
      </vxe-table-column>
      <vxe-table-column min-width="100">
        <vxe-table-column field="departmentName" title="部门" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.departmentName" placeholder="部门" clearable>
            <el-option
              v-for="item in departmentList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column min-width="100">
        <vxe-table-column field="name" title="姓名" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.name" placeholder="姓名" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="phone" title="联系电话" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.phone" placeholder="联系电话" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column min-width="100">
        <vxe-table-column field="positionName" title="职位" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.position" placeholder="职位" clearable>
            <el-option
              v-for="item in positionList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column min-width="100">
        <vxe-table-column field="employeeNumber" title="工号" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.employeeNumber" placeholder="工号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="enrollmentDate" title="入职日期" min-width="400" sortable show-header-overflow show-overflow />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="listQuery.enrollmentDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'enrollmentDate')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column min-width="100">
        <vxe-table-column field="employmentTypeText" title="用工类型" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.employmentType" placeholder="用工类型" clearable>
            <el-option
              v-for="item in employmentList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column min-width="100">
        <vxe-table-column field="outsourcerName" title="劳务外包方" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.outsourcer" placeholder="劳务外包方" clearable>
            <el-option
              v-for="item in outsourcerList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <!-- <vxe-table-column>
        <vxe-table-column field="planQuantity" title="活跃天数" min-width="210" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.planQuantityStart" placeholder="上限" type='number' style="width:80px;" />
          -
          <el-input v-model="listQuery.planQuantityEnd" placeholder="下限" type='number' style="width:80px;" />
        </template>
      </vxe-table-column>
      <vxe-table-column min-width="100">
        <vxe-table-column field="staffGrade" title="员工等级" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.staffGrade" placeholder="员工等级" clearable />
        </template>
      </vxe-table-column> -->
      <vxe-table-column title="操作" fixed="right" min-width="100">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row.code, scope.row.branchCode, scope.row.departmentName)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
    <vxe-modal v-model="modelAddFlag" title="新增" width="600" height="580" destroy-on-close resize>
      <compAdd ref="addRef"  @fatherAddMethod="fatherAdd" @fatherCancelMethod="fatherCancel" />
    </vxe-modal>
    <vxe-modal v-model="modelEditFlag" title="编辑" width="600" height="580" destroy-on-close resize>
      <compEdit :staffRef="staffRef" :staffEdits='staffEdits' @fatherEditMethod="fatherEdit" @fatherCancelMethod="fatherCancel" />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
import compAdd from './components/staffAdd.vue'
import compEdit from './components/staffEdit.vue'
import compDetail from './components/staffDetail.vue'
import request from '@/utils/request'
import groupSelect from "./components/groupSelect";
import { dataConversionUtil } from './components/excel.js'
import { exportStaffList, getDepartmentList, listDict } from "@/api/store";

export default {
  name: '员工管理',
  components: {
    compAdd,
    compEdit,
    compDetail,
    groupSelect
  },
  data() {
    return {
      // 日期选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      employmentList: [
        {
          code: 'regular',
          name: '正式工'
        },{
          code: 'temp',
          name: '临时工'
        },{
          code: 'out',
          name: '外包工'
        }
      ],
      departmentList: [],
      message: '',
      loading: false,
      cascadeData:[],
      tableData: [],
      modelAddFlag: false,
      modelEditFlag: false,
      modelDetailFlag: false,
      exportAllloading:false, //导出全部弹窗状态
      copy: false,
      allAlign:'center',
      listQuery: {
        partyType: 'STAFF',
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      roleList: [],
      staffRef:'', //新传值
      organization:[],
      staffEdits:[],
      positionList: [],
      outsourcerList: []
    }
  },
  created() {
    this.getCascadeData()
    this.findList()
  },
  methods: {
    setOrgCode(value) {
      if(!value)return
      this.listQuery.branchCode = value[0]
      this.listQuery.departmentCode = value[1]
      this.listQuery.teamCode = value[2]
      getDepartmentList(value[0]).then(response => {
        this.departmentList = response.data
      })
    },
    groupNameFormatter({ row }) {
      let gropName = row.branchName;
      if(row.departmentName)
        gropName =gropName + ' / ' + row.departmentName;
      if(row.teamName)
        gropName =gropName + ' / ' + row.teamName;
      return gropName
    },
    // 获取字典数据 = 职位、劳务外包方
    getCascadeData() {
      listDict('positionType').then(response => {
        this.positionList = response.data[0].dictList
      })
      listDict('outsourcerType').then(response => {
        this.outsourcerList = response.data[0].dictList
      })
    },
    findList() {
      this.loading = true
      return new Promise(resolve => {
        request({
          url: '/arpa-basic-api/staffs',
          method: 'get',
          params: this.listQuery
        }).then(response => {
          this.tableData = response.data.records
          this.listQuery.total = response.data.total
          this.loading = false
          resolve();
        });
      });
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
        if(property === 'employmentTypeText'){
          this.listQuery.sortField = 'employmentType'
        }
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },
    // 添加方法
    funcAdd() {
      this.modelAddFlag = true
    },
    // 修改方法
    funcEdit(code, branchCode ,departmentName) {
      this.staffRef = code
      const staffEdit = [
        branchCode = branchCode,
        departmentName = departmentName
      ]
      this.staffEdits = staffEdit
      this.modelEditFlag = true
    },
    // 删除方法
    funcDelete(row) {
      this.$confirm('确认删除吗？')
        .then(_ => {
          request({
            url: `/arpa-basic-api/party/`,
            method: 'delete',
            params: { codes: row }
          }).then(response => {
            this.$message({ message: response.msg, type: 'success' })
            this.findList()
          })
        })
        .catch(_ => {})
    },
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    changeStartDate(value) {
      this.listQuery.gmtCreatedStart = value + ' 00:00:00'
    },
    changeEndDate(value) {
      this.listQuery.gmtCreatedEnd = value + ' 23:59:59'
    },
    // 导出全部
    AllDataEventAll () {
      this.exportAllloading = true
      exportStaffList(this.listQuery).then(data => {
      let tableHeader = [
        ['姓名','联系电话', '所属机构','创建时间'],
      ]
      let dataList = []
      data.data.records.forEach(v=>{
        dataList.push([v.name, v.phone,v.branchName+'/'+v.departmentName,v.gmtCreated])
      })
      dataConversionUtil.dataToExcel('数据',tableHeader, dataList);
      }).finally(()=>{
        this.exportAllloading = false
      })
    },
    // 增加组件的父方法
    fatherAdd() {
      this.modelAddFlag = false
      this.findList()
    },
    // 编辑组件的父方法
    fatherEdit() {
      this.modelEditFlag = false
      this.findList()
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case 'add':
          this.modelAddFlag = false
          break
        case 'edit':
          this.modelEditFlag = false
          break
        case 'detail':
          this.modelDetailFlag = false
          break
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },
    // 角色名
    formatterRoleName({ cellValue }) {
      let roleNames = ''
      if (cellValue && cellValue.length > 0) {
        cellValue.forEach(function(val, index, arr) {
          roleNames += val.roleName + ' '
        })
      }
      return roleNames
    }
  }
}
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
